//
//  ReadListInfoViewController.m
//  Leisure
//
//  Created by xalo on 16/6/30.
//  Copyright © 2016年 朱旭东. All rights reserved.
//

#import "ReadListInfoViewController.h"

@interface ReadListInfoViewController ()<UIWebViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)NSString *html;
@property(nonatomic,strong)UITableView *tableView;//评论列表
@property(nonatomic,strong)NSMutableArray *dataArray;//评论数组
@property(nonatomic,strong)CommentView *comentView;//评论视图
@end

@implementation ReadListInfoViewController

#pragma mark -------懒加载--------------

- (CommentView *)comentView
{
    if (!_comentView) {
        //从XIB中获取View
        _comentView  =[[NSBundle mainBundle] loadNibNamed:@"ComentView" owner:nil options:nil].lastObject;
        _comentView.frame = CGRectMake(0, kheight-50, kwidth,  50);
    
    }
    return _comentView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray  ;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kwidth, kheight-64-50) style:UITableViewStylePlain] ;
    }
    _tableView.dataSource = self;
    _tableView.delegate =self;
    return _tableView;
}
- (UIWebView *)webView
{
    if (!_webView) {
        _webView =[[UIWebView  alloc] initWithFrame:self.view.frame] ;
        _webView.delegate = self;
        _webView.scrollView.bounces = NO;
        _webView.scrollView.bouncesZoom = NO;
        _webView.userInteractionEnabled = NO;
    }
    return _webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    //请求数据
    [RequestManager  fetchDataWithURL:kReadListInfoUrl parameters:@{@"contentid":self.readListModel.ID} method:@"POST" complet:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        //根据<pre>去分隔
        NSArray *array = [dic[@"data"][@"html"] componentsSeparatedByString:@"<pre>"];
        [self.webView  loadHTMLString:array[0] baseURL:nil];
        self.html = array[0];
        
    } updataUI:^{
        
        //添加发送事件
        [self.comentView.sendBtn addTarget:self action:@selector(comentSendAction) forControlEvents:UIControlEventTouchUpInside];
    }];
    
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL  URLWithString:@"http://www.baidu.com"]]];
    
    [self.tableView  registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
   
    //键盘弹出通知
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //键盘回收通知
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(keyBoardWillHid:) name:UIKeyboardWillHideNotification object:nil];

}

//获取评论
- (void)fetchCommentWith:(void(^)())block{
    //评论请求
    [RequestManager  fetchDataWithURL:kCommentUrl parameters:@{@"contentid":self.readListModel.ID} method:@"POST" complet:^(NSData *data) {
        
        NSDictionary *dic  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        for (NSDictionary *subDic in dic[@"data"][@"list"]) {
            [self.dataArray addObject:subDic[@"content"]];
        }
        
    } updataUI:^{
        [self.tableView reloadData];
                if (block) {
                    block();
                }
    }];
    [_comentView.textFiled  resignFirstResponder];
}


//评论事件
- (void)comentSendAction{
    
    
    [RequestManager  fetchDataWithURL:kSendCommentUrl parameters:@{@"auth":@"CcJvRS7m1m3m35DCsh1HMTtlzJxQcT4MuSK8jttDGYm3cWP22tJJShlV7m3s",@"contentid":self.readListModel.ID  ,@"content":self.comentView.textFiled.text } method:@"POST" complet:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization  JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        
    } updataUI:^{
        
        
        //清空元数组中的数据
        [self.dataArray removeAllObjects];

        [self fetchCommentWith:^{
        if (self.dataArray.count > 0 ) {
                        [self.tableView  scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                    }
                }];
        }];
    
}


//收藏事件
- (void)itemAcion{

        [[CoreDataManager defaultManager] insertCollectionMmodelWothModel:self.readListModel html:self.html];

   
}
#pragma mark -------UIWebViewDelegate----------------------

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"加载完成");

    //正则表达式，屏幕自适应
        NSString *js = @"function imgAutoFit() { \
        var imgs = document.getElementsByTagName('img'); \
        for (var i = 0; i < imgs.length; ++i) {\
        var img = imgs[i];   \
        img.style.maxWidth = %f;   \
//        } \
        }";
        js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
        
        [webView stringByEvaluatingJavaScriptFromString:js];
        [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];

        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(itemAcion)];
    
    [self  fetchCommentWith:NULL];
    
    //改变webview的Frame
   CGFloat height =  [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];

    NSLog(@"%f",height);
    CGRect webViewFrame = _webView.frame;
    //js可能会影响webView的高度，给他加10
    webViewFrame.size.height = height+10;
    webView.frame = webViewFrame;
    
    self.tableView.tableHeaderView = self.webView;
    [self.view addSubview:self.tableView];
    [self.view  addSubview:self.comentView];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"开始加载");
}

#pragma mark -------------UITableVIewDelegate----------------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell  =[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}

#pragma mark -----键盘回收方法------

//键盘弹出通知
- (void)keyBoardWillShow:(NSNotification*)sender{
    
    NSLog(@"键盘出来了");
    
    //拿到键盘的frame
    CGRect keyBoardRect  = [sender.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    CGRect frame = self.view.frame;
    frame.origin.y =  - keyBoardRect.size.height ;
    self.view.frame = frame;
    
}


//键盘回收通知
- (void)keyBoardWillHid:(NSNotification*)sender{
    NSLog(@"键盘消失了");
    self.view.frame = [UIScreen mainScreen].bounds;
    
}

@end
